<template>
  <div>
    <!-- 商品Excel导入对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="导入商品数据"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="!importing"
      :show-close="!importing"
    >
      <div class="import-dialog-content">
        <div class="import-tip">
          <p>请上传按模板格式编辑的Excel文件</p>
          <el-button type="primary" link @click="downloadTemplate">下载导入模板</el-button>
        </div>
        
        <el-upload
          class="excel-uploader"
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :file-list="fileList"
          accept=".xlsx,.xls"
          :disabled="importing"
        >
          <el-button type="primary" :icon="Upload" :disabled="importing">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传xlsx或xls格式的Excel文件
            </div>
          </template>
        </el-upload>
        
        <!-- 进度条区域 -->
        <div v-if="showProgress" class="import-progress">
          <div class="progress-info">
            <span>导入进度: {{ importCurrent }}/{{ importTotal }}</span>
            <span>{{ importProgress }}%</span>
          </div>
          <el-progress 
            :percentage="importProgress" 
            :status="importProgress === 100 ? 'success' : ''"
            :stroke-width="18"
            :format="() => ''"
          ></el-progress>
          
          <div class="progress-status" v-if="importProgress < 100">
            <el-icon class="loading-icon"><Loading /></el-icon>
            <span>正在导入第 {{ importCurrent }} 条数据...</span>
          </div>
          
          <div class="progress-status completed" v-else>
            <el-icon class="success-icon"><Check /></el-icon>
            <span>导入完成！</span>
          </div>
          
          <div class="progress-stats">
            <div class="stat-item">
              <span class="stat-label">成功:</span>
              <span class="stat-value success">{{ importSuccess }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">失败:</span>
              <span class="stat-value error">{{ importFailed }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">总计:</span>
              <span class="stat-value">{{ importCurrent }}/{{ importTotal }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog" :disabled="importing">取 消</el-button>
          <el-button type="primary" @click="handleImport" :loading="importing" :disabled="importing">
            {{ importing ? '导入中...' : '导入' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {Upload, Loading, Check} from '@element-plus/icons-vue'
import { ref, defineEmits, watch, defineProps } from 'vue'
import * as XLSX from 'xlsx';
import { ElMessage } from 'element-plus';
import http from "@/utils/request";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  apiUrl: {
    type: String,
    default: '/product/create'
  }
});

const emit = defineEmits(['update:visible', 'import-success']);

// Excel导入相关
const dialogVisible = ref(false);
const fileList = ref([]);
const importing = ref(false);
const importProgress = ref(0);
const importTotal = ref(0);
const importCurrent = ref(0);
const showProgress = ref(false);
const importSuccess = ref(0);
const importFailed = ref(0);

// 监听visible属性变化
watch(() => props.visible, (val) => {
  dialogVisible.value = val;
  if (val) {
    // 打开对话框时重置状态
    resetImportState();
  }
});

// 监听dialogVisible变化
watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val);
});

// 重置导入状态
const resetImportState = () => {
  fileList.value = [];
  importProgress.value = 0;
  importTotal.value = 0;
  importCurrent.value = 0;
  importSuccess.value = 0;
  importFailed.value = 0;
  showProgress.value = false;
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
};

// 处理文件变化
const handleFileChange = (file) => {
  fileList.value = [file];
  return false; // 阻止自动上传
};

// 下载模板
const downloadTemplate = () => {
  // 创建简单的Excel模板
  const template = [
    ['商品名称', '商品分组ID', '库存', '价格', '折扣', '简介', '是否上架(1是/2否)'],
    ['示例商品', '1', '100', '199.99', '0.95', '这是一个示例商品', '1']
  ];

  // 生成excel
  const ws = XLSX.utils.aoa_to_sheet(template);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, '商品导入模板.xlsx');
};

// 处理Excel导入
const handleImport = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择Excel文件');
    return;
  }

  const file = fileList.value[0].raw;
  if (!file) {
    ElMessage.warning('文件读取失败');
    return;
  }

  // 检查文件类型
  const fileType = file.name.split('.').pop().toLowerCase();
  if (fileType !== 'xlsx' && fileType !== 'xls') {
    ElMessage.error('请上传Excel文件(xlsx或xls格式)');
    return;
  }

  importing.value = true;
  // 重置进度状态
  importProgress.value = 0;
  importTotal.value = 0;
  importCurrent.value = 0;
  importSuccess.value = 0;
  importFailed.value = 0;
  showProgress.value = false;

  try {
    const reader = new FileReader();
    reader.onload = async (e) => {
      try {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
        const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });

        // 检查数据是否至少包含表头和一行数据
        if (!jsonData || jsonData.length < 2) {
          ElMessage.error('Excel文件格式不正确或数据为空');
          importing.value = false;
          return;
        }

        // 检查表头是否包含必要字段
        const headers = jsonData[0];
        if (!headers.includes('商品名称') || !headers.includes('价格')) {
          ElMessage.error('Excel文件缺少必要的字段（商品名称、价格等）');
          importing.value = false;
          return;
        }

        // 移除表头，获取实际数据
        const productsData = jsonData.slice(1);

        // 将Excel数据转为商品对象数组
        const products = productsData.map(row => {
          const nameIndex = headers.indexOf('商品名称');
          const groupIndex = headers.indexOf('商品分组ID');
          const stockIndex = headers.indexOf('库存');
          const priceIndex = headers.indexOf('价格');
          const discountIndex = headers.indexOf('折扣');
          const summaryIndex = headers.indexOf('简介');
          const stateIndex = headers.indexOf('是否上架(1是/2否)');

          return {
            name: row[nameIndex] || '',
            productGroup: row[groupIndex] || '',
            stockNum: row[stockIndex] || 0,
            price: row[priceIndex] || 0,
            discount: row[discountIndex] || 1,
            summary: row[summaryIndex] || '',
            state: row[stateIndex] || 1
          };
        });

        // 过滤掉名称为空的商品
        const validProducts = products.filter(p => p.name && p.name.trim() !== '');

        if (validProducts.length === 0) {
          ElMessage.error('没有有效的商品数据');
          importing.value = false;
          return;
        }

        // 显示进度条并设置总数
        showProgress.value = true;
        importTotal.value = validProducts.length;
        
        // 逐个导入商品并更新进度
        for (let i = 0; i < validProducts.length; i++) {
          importCurrent.value = i + 1;
          importProgress.value = Math.round((importCurrent.value / importTotal.value) * 100);

          try {
            const response = await http.post(props.apiUrl, validProducts[i]);
            if (response.code === 200) {
              importSuccess.value++;
            } else {
              importFailed.value++;
              console.error(`导入商品失败：${response.msg}`);
            }
          } catch (error) {
            importFailed.value++;
            console.error('导入商品时出错:', error);
          }
        }

        // 导入完成后的提示和操作
        if (importSuccess.value > 0) {
          ElMessage.success(`导入完成：成功${importSuccess.value}个，失败${importFailed.value}个`);
          
          // 通知父组件导入成功，可以刷新数据
          emit('import-success', {
            success: importSuccess.value,
            failed: importFailed.value,
            total: importTotal.value
          });
          
          // 延迟关闭对话框，让用户看到最终进度
          setTimeout(() => {
            dialogVisible.value = false;
            showProgress.value = false;
          }, 500);
        } else {
          ElMessage.error('导入失败：没有成功导入的商品');
        }
      } catch (error) {
        console.error('处理Excel文件时出错:', error);
        ElMessage.error('Excel文件处理失败');
      } finally {
        importing.value = false;
      }
    };

    reader.onerror = () => {
      ElMessage.error('读取文件失败');
      importing.value = false;
    };

    reader.readAsArrayBuffer(file);
  } catch (error) {
    console.error('导入过程中出错:', error);
    ElMessage.error('导入过程中出错');
    importing.value = false;
  }
};
</script>

<style scoped>
/* Excel导入样式 */
.import-dialog-content {
  margin-bottom: 20px;
}

.import-tip {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: #f8f8f8;
  padding: 10px 15px;
  border-radius: 4px;
}

.import-tip p {
  margin: 0;
  color: #606266;
}

.excel-uploader {
  width: 100%;
}

.excel-uploader .el-upload {
  width: 100%;
  text-align: center;
}

.el-upload__tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.import-progress {
  margin-top: 20px;
  padding: 15px;
  border-radius: 4px;
  background-color: #f8f8f8;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  animation: fadeIn 0.5s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.progress-status {
  display: flex;
  align-items: center;
  margin: 10px 0;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f0f9eb;
  color: #67c23a;
  transition: all 0.3s ease;
}

.progress-status.completed {
  background-color: #f0f9eb;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { background-color: #f0f9eb; }
  50% { background-color: #e1f3d8; }
  100% { background-color: #f0f9eb; }
}

.loading-icon {
  margin-right: 8px;
  font-size: 16px;
  animation: spin 1.5s linear infinite;
}

.success-icon {
  margin-right: 8px;
  font-size: 16px;
  color: #67c23a;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.progress-stats {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #dcdfe6;
}

.stat-item {
  text-align: center;
  padding: 0 15px;
}

.stat-label {
  display: block;
  margin-bottom: 5px;
  font-size: 13px;
  color: #606266;
}

.stat-value {
  font-weight: bold;
  font-size: 18px;
}

.success {
  color: #67C23A;
}

.error {
  color: #F56C6C;
}

:deep(.el-progress-bar__inner) {
  transition: width 0.3s ease;
}

:deep(.el-progress-bar__outer) {
  background-color: #e9e9e9;
}
</style> 